<?php
namespace app\store\controller\shouhuo;

use app\store\model\Device as DeviceModel;

class Device extends Base
{
    /**
     * 设备
     */

    protected $domain = 'https://testopenapi.ksepton.com/open-service'; //星云开物域名
    protected $app_key = 'EP2024241620268';
    protected $app_secret = 'e43f8120a7u94cb4c8515294233a2b12';

    public function obj(){
        return new DeviceModel();
    }

    //列表
    public function index()
    {
        $res = $this->obj()->index();
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $list = $res['data'];
        $total = $res['total'];
        return $this->fetch('index', compact('list', 'total'));
    }

    //添加
    public function add()
    {
        //页面
        if (!$this->request->isAjax()) {
            return $this->fetch('add');
        }
        //数据
        $pas = $this->request->param();
        if (!$pas['shop_name']) {
            return $this->renderError('商户必须的');
        }
        if (!$pas['title']) {
            return $this->renderError('设备名称必须的');
        }
        if (!$pas['imei']) {
            return $this->renderError('设备编号必须的');
        }
        if (!$pas['door01_no']) {
            return $this->renderError('门编号必须的');
        }
        if (!$pas['door01_name']) {
            $pas['door01_name'] = 'M'.date('YmdHis', time()).rand(100, 999);
        }
        if ($pas['door02_no']) {
            $pas['door02_name'] = 'M'.date('YmdHis', time()).rand(100, 999);
        }
        $res = $this->obj()->add($pas);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        return $this->renderSuccess('添加成功', url('shouhuo.device/index'));
    }

    //修改
    public function modify()
    {
        $pas = $this->request->param();
        $id = isset($pas['id'])&&$pas['id'] ? $pas['id'] : 0;
        if (!$id) {
            return $this->renderError('没有ID');
        }
        $res = $this->obj()->getOne($id);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $list = $res['data'];
        //页面
        if (!$this->request->isAjax()) {
            return $this->fetch('edit', compact('list'));
        }
        //数据
        if (!$pas['shop_name']) {
            return $this->renderError('商户必须的');
        }
        if (!$pas['title']) {
            return $this->renderError('机器名称必须的');
        }
        if (!$pas['imei']) {
            return $this->renderError('机器号必须的');
        }
        if (!$pas['door01_id']) {
            return $this->renderError('门ID必须的');
        }
        if (!$pas['door01_no']) {
            return $this->renderError('门编号必须的');
        }
        if (!$pas['door01_name']) {
            $pas['door01_name'] = 'M'.date('YmdHis', time()).rand(100, 999);
        }
        if ($pas['door02_no']) {
            if (!$pas['door02_id']) {
                return $this->renderError('右门ID必须的');
            }
            $pas['door02_name'] = 'M'.date('YmdHis', time()).rand(100, 999);
        }
        $res = $this->obj()->modify($id, $pas);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        return $this->renderSuccess('修改成功', url('shouhuo.device/index'));
    }

    /**
     * 星云开物-同步机器列表
     */
    public function listByXykw()
    {
        $httpUrl = $this->domain.'/equipment/list';
        $httpData = [
            'page' => "1",
            'size' => "10",
        ];
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData);
        $xykw = $this->toCurl($httpUrl, 1, $httpData);
        if ($xykw['code'] < 0) {
            return $this->renderError($xykw['msg']);
        }
        $xykw = $xykw['data'];
        if ($xykw['code'] != 200) {
            return $this->renderError($xykw['message']);
        }
        $xykw = $xykw['data'];
        if (!$xykw) {
            return $this->renderError('没有记录');
        }
        $this->obj()->listByXykw($xykw);
        return redirect('/index.php?s=/store/shouhuo.device/index');
    }

    /**
     * 星云开物-设备绑定
     */
    public function bind()
    {
        $pas = $this->request->param();
        $id = isset($pas['id'])&&$pas['id'] ? $pas['id'] : 0;
        $res = $this->obj()->getOne($id);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $imei = $res['data']['imei'];
        $door01 = $res['data']['door01_no'];
        $door02 = $res['data']['door02_no'];
        if (!$imei) {
            return $this->renderError('设备编号必须的');
        }
        if (!$door01) {
            return $this->renderError('左门编号必须的');
        }
        //请求星云开物
        $httpUrl = $this->domain.'/equipment/bind';
        $httpData = [
            'imei' => $imei, //设备编号
            'left_equipment_id' => $door01, //左门编号
        ];
        if ($door02) {
            $httpData['right_equipment_id'] = $door02; //右门编号
        }
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData);
//        var_dump($httpUrl); echo '<br><br>';
//        var_dump($httpData); echo '<br><br>';
        $res = $this->toCurl($httpUrl, 1, $httpData);
//        ddd($res);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $xykw = $res['data'];
        if ($xykw['code'] != 200) {
            return $this->renderError($xykw['message']);
        }
        $res = $this->obj()->bind($id);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        return redirect('/index.php?s=/store/shouhuo.device/index');
    }

    /**
     * 星云开物-设备解绑
     */
    public function unbind()
    {
        $pas = $this->request->param();
        $id = isset($pas['id'])&&$pas['id'] ? $pas['id'] : 0;
        $type = isset($pas['type'])&&$pas['type'] ? $pas['type'] : 0;
        if (!$id) {
            return $this->renderError('ID不存在');
        }
        if (!$type) {
            return $this->renderError('门不存在');
        }
        $res = $this->obj()->getOne($id);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $imei = $res['data']['imei'];
        $door01 = $res['data']['door01_no'];
        $door02 = $res['data']['door02_no'];
        if ($type == 1) {
            $doorno = $door01;
        } else {
            if (!$door02) {
                return $this->renderError('右门不存在');
            }
            $doorno = $door02;
        }
        $httpUrl = $this->domain.'/equipment/unbind/imei';
        $httpData = [
            'imei' => $imei, //设备编号
            'third_equipment_id' => $doorno, //门编号
        ];
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData);
//        var_dump($httpUrl); echo '<br><br>';
//        var_dump($httpData); echo '<br><br>';
        $res = $this->toCurl($httpUrl, 1, $httpData);
//        ddd($res);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $xykw = $res['data'];
//        ddd($xykw);
        if ($xykw['code'] != 200) {
            return $this->renderError($xykw['message']);
        }
        $res = $this->obj()->unbind($id);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        return redirect('/index.php?s=/store/shouhuo.device/index');
    }

    /**
     * 星云开物-设备开门
     */
    public function doorOpen()
    {
        $pas = $this->request->param();
        $id = isset($pas['id'])&&$pas['id'] ? $pas['id'] : 0;
        $type = isset($pas['type'])&&$pas['type'] ? $pas['type'] : 1;
        if (!$id) {
            return $this->renderError('ID不存在');
        }
        if (!$type) {
            return $this->renderError('门不存在');
        }
        $res = $this->obj()->getOne($id);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $imei = $res['data']['imei'];
        $door01 = $res['data']['door01_no'];
        $door02 = $res['data']['door02_no'];
        if ($type == 1) {
            $doorno = $door01;
        } else {
            if (!$door02) {
                return $this->renderError('右门不存在');
            }
            $doorno = $door02;
        }
        $orderno = $this->orderno();
        $httpUrl = $this->domain.'/equipment/opendoor';
        $httpData = [
            'equipment_id' => $doorno, //门编号
            'type' => 'consume', //操作 consume 消费； manage 管理
            'order_sn' => $orderno,
//            'is_algorithm' => '',
        ];
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData);
//        var_dump($httpUrl); echo '<br><br>';
//        var_dump($httpData); echo '<br><br>';
        $logid = $this->obj()->orderAdd([
            'order_sn' => $orderno,
            'lly_url' => $httpUrl, 'lly_req' => $httpData,
            'door_info' => json_encode([
                'imei' => $imei, 'door_no' => $doorno,
            ]),
        ]); //订单日志
        $res = $this->toCurl($httpUrl, 1, $httpData);
        $this->obj()->orderModify($logid, ['lly_back' => json_encode($res, JSON_UNESCAPED_UNICODE)]); //订单日志
//        ddd($res);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        $xykw = $res['data'];
//        ddd($xykw);
        if ($xykw['code'] != 200) {
            return $this->renderError($xykw['message']);
        }
        $res = $this->obj()->doorOpen($id);
        if ($res['code'] < 0) {
            return $this->renderError($res['msg']);
        }
        return redirect('/index.php?s=/store/shouhuo.device/index');
    }

    /**
     * 构建CURL请求
     * @param string $url 请求地址
     * @param int $method 请求方式：0get，1post
     * @param string $sring 请求数据
     */
    public function toCurl($url, $method = 0, $string = '')
    {
        $headers = array(
            'Content-Type: application/json',
        );
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        if ($method) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $string);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=> -1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }

    /**
     * 接口签名
     * @param array $params 请求参数
     */
    public function apiSign($params)
    {
        ksort($params);
        $param = json_encode($params);
        $rand = $this->randStr(rand(10, 20));
        $signs = [
            'api_key' => $this->app_key,
            'data' => $param,
            'random_str' => $rand,
            'api_secret' => $this->app_secret,
        ];
        $str = '';
        foreach ($signs as $k => $v) {
            if ($str) {
                $str .= '&'.$k.'='.$v;
            } else {
                $str = $k.'='.$v;
            }
        }
        $str = md5($str);
        return [
            'random_str' => $rand,
            'data' => $params,
            'api_key' => $this->app_key,
            'sign' => $str,
        ];
    }

    /**
     * 生成随机字符串，默认数字字母混合
     * @param int $numeric 0纯数字
     */
    public function randStr($length = 6, $numeric = 1)
    {
        if(!$numeric) {
            //纯数字
            $str = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            //数字、字母组合
            $str = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $str .= $chars[mt_rand(0, $max)];
            }
        }
        return $str;
    }
}